package com.atguigu.serviceedu.controller;


import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exception.GuliException;
import com.atguigu.serviceedu.client.VodClient;
import com.atguigu.serviceedu.entity.EduVideo;
import com.atguigu.serviceedu.service.EduVideoService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author JY
 * @since 2021-01-19
 */
@Api(description="课时管理")
@RestController
@RequestMapping("/serviceedu/video")
//@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;

    @Autowired
    private VodClient vodClient;

    //新增小节
    @PostMapping("save")
    private R save(@RequestBody EduVideo video){
        videoService.save(video);
        return R.ok();
    }

    //根据id得到小节
    @GetMapping("getById/{id}")
    public R getById(@PathVariable String id){
        EduVideo video = videoService.getById(id);
        return R.ok().data("item",video);
    }

    //更新
    @PostMapping("update")
    public R update(@RequestBody EduVideo video){
        videoService.updateById(video);
        return R.ok();
    }

    //删除
    //要连着视频一起删除
    @DeleteMapping("delete/{id}")
    public R delete(@PathVariable String id){
        //先删除阿里云视频
        EduVideo video = videoService.getById(id);
        String videoSourceId = video.getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)){
            R r = vodClient.delete(videoSourceId);
            if(r.getCode()==20001){
                throw new GuliException(20001,"熔断器拦截，删除视频失败");
            }
        }
        //在删除小节
        boolean flag = videoService.removeById(id);
        return flag?R.ok():R.error().message("删除失败");
    }
}

